package com.mall.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.examination.mlib.bean.DefaultEntity;
import com.examination.mlib.bean.HomeDrugEntity;
import com.examination.mlib.constants.AllStringConstants;
import com.examination.mlib.constants.ClickApi;
import com.examination.mlib.constants.KitArouterConstants;
import com.examination.mlib.utils.LocationUtils;
import com.examination.mlib.view.CustomTabLayout;
import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.mall.MallUtils;
import com.mall.R;
import com.mall.bean.YSpecialBean;
import com.yilijk.base.network.RequestParams;
import com.yilijk.base.network.https.HttpCallBack;
import com.yilijk.base.network.https.HttpUtils;
import com.yilijk.base.utils.ALog;
import com.yilijk.base.utils.ClickUtils;
import com.yilijk.base.utils.GlideUtil;
import com.yilijk.base.utils.ListUtil;
import com.yilijk.base.utils.LoadingUtils;
import com.yilijk.base.utils.ToastUtils;
import com.youth.banner.Banner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.time.temporal.Temporal;
import java.util.ArrayList;
import java.util.List;

public class MallCardView extends LinearLayout implements TabLayout.OnTabSelectedListener {
    private Context context;
    private View contentView;
    private CustomTabLayout tabLayout;
    private List<YSpecialBean.ListBean> tabs = new ArrayList<>();
    private RecyclerView recyclerView;
    private List<HomeDrugEntity.DrugItemData> drugs = new ArrayList<>();
    private DrugAdapter drugAdapter;
    private String cardTitle;
    private TextView titleTv;
    private ImageView imageView;
    private String doctorId;
    private View cartMoreView;
    private final Gson gson = new Gson();

    public void setSpecialBean(YSpecialBean specialBean, String doctorId) {
        this.specialBean = specialBean;
        this.doctorId = doctorId;
        this.cardTitle = specialBean.getTitle();
        if (!TextUtils.isEmpty(cardTitle)) {
            titleTv.setText(cardTitle);
        }
        if (!TextUtils.isEmpty(specialBean.getTitleColor())) {
            titleTv.setTextColor(Color.parseColor(specialBean.getTitleColor()));
        } else {
            titleTv.setTextColor(getResources().getColor(R.color.color_333));
        }

        tabs.clear();
        for (YSpecialBean.ListBean listBean : specialBean.getList()) {
            tabs.add(listBean);
            TabLayout.Tab tab = tabLayout.newTab();
            tab.setText(listBean.getSubTitle());
            tabLayout.addTab(tab);
        }
        if (tabs.get(0) != null) {
            getCartDrug(tabs.get(0).getId());
        }
        tabLayout.removeOnTabSelectedListener(this);
        tabLayout.addOnTabSelectedListener(this);
        if (specialBean.getSpecial() != null && !TextUtils.isEmpty(specialBean.getSpecial().getImgUrl())) {
            imageView.setVisibility(VISIBLE);
            GlideUtil.load(context, specialBean.getSpecial().getImgUrl(), imageView, R.drawable.icon_default_rectangle);
        } else {
            imageView.setVisibility(GONE);
        }
        ClickUtils.setFastOnClickListener(cartMoreView, new OnClickListener() {
            @Override
            public void onClick(View v) {
                ClickUtils.sendEvent(ClickApi.Mall.click_drugscardmore, context, "首页药品模块更多点击");
                Bundle bundle = new Bundle();
                bundle.putString("title", specialBean.getTitle());
                ArrayList<String> ids = new ArrayList<>();
                ids.add(specialBean.getCategoryId());
                bundle.putStringArrayList("frontCategoryIds", ids);
                if (!TextUtils.isEmpty(doctorId)) {
                    bundle.putString("doctorId", doctorId);
                }
                DefaultEntity.DataBean whCityBean = LocationUtils.getInstance().getWhCityBean();
                AMapLocation aMapLocation = LocationUtils.getInstance().getaMapLocation();
                if (whCityBean != null && !TextUtils.isEmpty(whCityBean.getProvinceName()) && !TextUtils.isEmpty(whCityBean.getCityName())) {
                    bundle.putString("whCity", whCityBean.getProvinceName() + "," + whCityBean.getCityName());
//                    paramsJSON.put("lat", whCityBean.getLat());
//                    paramsJSON.put("lng", whCityBean.getLng());
                } else if (aMapLocation != null && !TextUtils.isEmpty(aMapLocation.getProvince()) && !TextUtils.isEmpty(aMapLocation.getCity())) {
                    bundle.putString("whCity", aMapLocation.getProvince() + "," + aMapLocation.getCity());
//                    paramsJSON.put("lat", aMapLocation.getLatitude());
//                    paramsJSON.put("lng", aMapLocation.getLongitude());
                }
//                bundle.putString("frontCategoryId", specialBean.getCategoryId());
                MallUtils.push(context, KitArouterConstants.CART_DOCTORBUNDLE, KitArouterConstants.Cart.Retailers, bundle);
            }
        });

    }

    private YSpecialBean specialBean;

    public MallCardView(Context context) {
        super(context);
        init(context, null);
    }

    public MallCardView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public MallCardView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    public MallCardView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        this.context = context;
        contentView = LayoutInflater.from(context).inflate(R.layout.view_mall_card, this);
        tabLayout = contentView.findViewById(R.id.tablayout);
        recyclerView = contentView.findViewById(R.id.recycler_view);
        titleTv = contentView.findViewById(R.id.title_tv);
        imageView = contentView.findViewById(R.id.image_view);
        cartMoreView = contentView.findViewById(R.id.ll_cart_more);

        if (attrs != null) {
            TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.mall_card);
            cardTitle = typedArray.getString(R.styleable.mall_card_cardTitle);
            if (!TextUtils.isEmpty(cardTitle)) {
                titleTv.setText(cardTitle);
            }
            typedArray.recycle();
        }

        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        drugAdapter = new DrugAdapter(context, drugs);
        recyclerView.setAdapter(drugAdapter);

        tabLayout.setTabLayoutTextSize_select(R.style.mall_tab_select, R.style.mall_tab_unselect);

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        int position = tab.getPosition();
        if (ListUtil.getSize(tabs) > position) {
            getCartDrug(tabs.get(position).getId());
        }

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

    private void getCartDrug(String id) {
        LoadingUtils.getLoadingUtils(context).showLoading();
        RequestParams params = new RequestParams();
        params.put("pageIndex", 1);
        params.put("pageSize", 10);
        params.put("doctorId", this.doctorId);
        params.put("containVirtualService", false);
//        params.put("frontCategoryId", "[" + id + "]");
//        params.put("frontCategoryIds", id);
        params.put("blockList", id);
//        ArrayList<String> ids = new ArrayList<>();
//        ids.add(id);
//        params.put("frontCategoryIds", ids);
        HttpUtils.get(AllStringConstants.MallUrl.commoditySearch, params, new HttpCallBack<Object>() {
            @Override
            public void onSuccess(Object bean, int i) {
                LoadingUtils.getLoadingUtils(context).dismissLoading();
                String searchStr = gson.toJson(bean);
                try {
                    JSONObject jsonObject = new JSONObject(searchStr);
                    if (jsonObject.has("code")) {
                        int code = jsonObject.getInt("code");
                        if (code == 200 && jsonObject.has("data")) {
                            JSONObject dataJson = jsonObject.getJSONObject("data");
                            if (dataJson != null && dataJson.has(id)) {
                                JSONArray drugJsonArray = dataJson.getJSONArray(id);
                                List<HomeDrugEntity.DrugItemData> listBeans = gson.fromJson(drugJsonArray.toString(), new TypeToken<List<HomeDrugEntity.DrugItemData>>() {
                                }.getType());
                                drugs.clear();
                                drugs.addAll(listBeans);
                                drugAdapter.notifyDataSetChanged();
                                if (ListUtil.getSize(drugs) > 0) {
                                    recyclerView.scrollToPosition(0);
                                }
                            }
                        }
                    }

                } catch (Throwable e) {
                    e.printStackTrace();
                }

//                if (i == 200 && bean != null && "200".equals(bean.getStatus()) && bean.getData() != null) {
//                    List<MallDrugBean.ListBean> listBeans = bean.getData().getList();
//                    drugs.clear();
//                    drugs.addAll(listBeans);
//                    drugAdapter.notifyDataSetChanged();
//                    if (ListUtil.getSize(drugs) > 0) {
//                        recyclerView.scrollToPosition(0);
//                    }
//                } else if (bean != null && !TextUtils.isEmpty(bean.getMessage())) {
//                    ToastUtils.showShort(bean.getMessage());
//                }

            }

            @Override
            public void onFailure(String s, int i) {
                LoadingUtils.getLoadingUtils(context).dismissLoading();
            }
        });
    }


    private class DrugAdapter extends RecyclerView.Adapter {
        private Context context;
        private List<HomeDrugEntity.DrugItemData> drugList;

        public DrugAdapter(Context context, List<HomeDrugEntity.DrugItemData> drugList) {
            this.context = context;
            this.drugList = drugList;
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.view_item_card_drug, parent, false);
            return new DrugVH(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof DrugVH) {
                ((DrugVH) holder).setData(position);
            }
        }

        @Override
        public int getItemCount() {
            return ListUtil.getSize(drugList);
        }

        private class DrugVH extends RecyclerView.ViewHolder {

            private ImageView drugIv;
            private TextView drugNameTv, drugPriceTv;

            public DrugVH(@NonNull View itemView) {
                super(itemView);
                drugIv = itemView.findViewById(R.id.iv_drug);
                drugNameTv = itemView.findViewById(R.id.tv_drug_name);
                drugPriceTv = itemView.findViewById(R.id.tv_drug_price);
            }

            public void setData(int position) {
                if (ListUtil.getSize(drugList) > position) {
                    HomeDrugEntity.DrugItemData bean = drugList.get(position);

                    GlideUtil.load(context, bean.getImageUrl(), drugIv, R.drawable.icon_default_square);
                    drugNameTv.setText(bean.getName());
                    drugPriceTv.setText(bean.getPrice());

                    ClickUtils.setFastOnClickListener(itemView, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ClickUtils.sendEvent(ClickApi.Mall.click_drugscard, context, "首页药品模块点击");
                            Bundle bundle = new Bundle();

                            if ("drug".equals(bean.getCommodityType())) {
//                                bundle.putString("id", "" + bean.getDrugId());
                                bundle.putString("id", "" + bean.getCommodityId());
                            } else {
//                                bundle.putString("packetId", "" + bean.getPacketId());
                                bundle.putString("packetId", "" + bean.getCommodityId());
                            }
                            if (!TextUtils.isEmpty(doctorId)) {
                                bundle.putString("doctorId", "" + doctorId);
                            }
                            ALog.e("oakkk", "bundle: " + bundle.toString());
                            MallUtils.push(context,
                                    KitArouterConstants.CART_DOCTORBUNDLE,
                                    KitArouterConstants.Cart.DrugDetail,
                                    bundle);
                        }
                    });

                }
            }
        }
    }
}
